package kz.pompei.OneGwt.ifaces.widget.gwtadapters;

import kz.pompei.OneGwt.ifaces.util.Handler;
import kz.pompei.OneGwt.ifaces.util.HandlerKiller;
import kz.pompei.OneGwt.ifaces.util.StrUtil;
import kz.pompei.OneGwt.ifaces.widget.TextWidget;

import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.TextBoxBase;

public class TextBoxBase_impl_TextWidget implements TextWidget {
  private final TextBoxBase widget;
  
  public TextBoxBase_impl_TextWidget(TextBoxBase widget) {
    this.widget = widget;
  }
  
  @Override
  public String get() {
    return widget.getText();
  }
  
  private boolean skipHandleChange = false;
  
  @Override
  public void set(String t) {
    widget.setText( t );
    skipHandleChange = true;
  }
  
  @Override
  public void setVisible(boolean visible) {
    widget.setVisible( visible );
  }
  
  @Override
  public void setEnabled(boolean enabled) {
    widget.setEnabled( enabled );
  }
  
  @Override
  public void setFocus(boolean focused) {
    widget.setFocus( focused );
  }
  
  @Override
  public HandlerKiller addChangeHandler(final Handler handler) {
    final HandlerRegistration hr = widget.addKeyUpHandler( new KeyUpHandler() {
      private String currentValue = widget.getText();
      
      @Override
      public void onKeyUp(KeyUpEvent event) {
        String newValue = widget.getText();
        
        if (!StrUtil.strEq( currentValue, newValue )) {
          currentValue = newValue;
          if (skipHandleChange) {
            skipHandleChange = false;
          } else {
            handler.handle();
          }
        }
      }
    } );
    
    return new HandlerKiller() {
      @Override
      public void killHandler() {
        hr.removeHandler();
      }
    };
  }
}
